package cn.stu.system.config.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.stu.common.utils.JwtHelper;
import cn.stu.common.utils.UserHolder;
import cn.stu.common.dto.UsersDto;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static cn.stu.common.utils.SystemConstants.LOGIN_USER_KEY;
import static cn.stu.common.utils.SystemConstants.LOGIN_USER_TTL;


public class RefreshTokenInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        Long userId = JwtHelper.getUserId(token);
        if (userId == null) {
            return true;
        }
        //生成tokenKey
        String key = LOGIN_USER_KEY + userId;
        //判断tokenKey是否存在
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(key))) {
            //不存在，跳过此拦截器
            return true;
        }
        //获取redis中token进行进一步验证
        String redisToken = stringRedisTemplate.opsForValue().get(key);
        //判断用户是否为登录者
        if (!token.equals(redisToken)) {
            //不是当前登录者，账号在别处登录
            response.setStatus(402);
            return false;
        }
        String sessionId = JwtHelper.getSessionId(token);
        //将数据存为UserDTO
        UsersDto user = new UsersDto();
        user.setUserId(userId);
        user.setSessionId(sessionId);
        // 6.存在，保存用户信息到 ThreadLocal
        UserHolder.saveUser(user);
        // 7.刷新token有效期
        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.SECONDS);
        // 8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
